#include "database.hpp"

Database::Database()
{
	databaseName = "db";
	db = new QSqlDatabase();
        *db = QSqlDatabase::addDatabase("QSQLITE");
}

int Database::login(QString name, QString password)
{
	if (open())
	{
		QSqlQuery query = db->exec("SELECT * FROM Medecin WHERE nom = '" + name + "' AND pass = '" + password + "';");
		if (query.lastError().text() != " ")
		{
			qDebug() << query.lastError().text();
			close();
			return -1;
		}

		int nbLines = 0;
		while (query.next()) nbLines++;

		if (nbLines == 1)
		{
			query = db->exec("SELECT idmedecin FROM Medecin WHERE nom = '" + name + "';");
			query.next();
			close();
			return query.value(0).toInt(); // Return the id
		}
	}
	close();
	return -1;
}

int Database::findId(QString name)
{
	if (open())
	{
		QSqlQuery query = db->exec("SELECT idmedecin FROM Medecin WHERE nom = '" + name + "';");
		query.next();
		close();
		return query.value(0).toInt();
	}
	close();
	return -1;
}

int Database::open()
{
	db->setDatabaseName(databaseName);
	if (db->open())	return 1;
	else
	{
		qDebug() << "Error : " << db->lastError().text();
		return 0;
	}
}

void Database::close()
{
	db->close();
}
